<template>
  <div>
    <div id="map2" @touchstart="putup"></div>
    <div class="search">
      <div class="search-con">
        <span class="search-icon"></span>
        <input type="text" class="search-in" @input="searchin" id="suggestId" @blur="searchcancel">
        <div class="search-line"></div>
        <div class="search-cancel" @click.stop="searchcancel">取消</div>
        <div class="search-cover" v-show="scover" @click.prevent.stop="searchcover">
          <span class="search-icon search-icon1"></span>
          <span>{{backpoint}}</span>
        </div>
      </div>
    </div>
    <!--focus-->
    <div class="search-history">
      <p class="history-title">历史记录</p>
      <ul>
        <li v-for="v in historydata" :data-lng="v.lng" :data-lat="v.lat" class="historylist">{{v.title}}</li>
      </ul>
    </div>
    <!--input-->
    <div class="search-list" id="searchResultPanel">
    </div>
    <div id="rebackpark"  >
      <div class="rebackpark" @touchstart="drag">
        <div class="parkTop" v-html="gettop">
        </div>
        <div class="parklist">
          <ul>
            <li v-for="v in parkdetail" :data-parkingid="v.parkingId" :data-parkinglat="v.parkingLat" :data-parkinglng="v.parkingLon" :data-carcount="v.carCount" :data-parkingkind="v.parkingKind" :data-parkname="v.parkingName" class="backpark">
              <div class="parkname">
                <div class="circle"></div>
                <div class="park ellipsis">{{v.parkingName}}</div>
                <div class="distance">{{v.distance}}米</div>
                <div class="moneyicon" v-if="v.parkingKind == 0"></div>
              </div>
              <div class="parkaddress">
                {{v.parkingAddress}}
              </div>
              <div class="chose"></div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="rebackbg">
      <div class="choosecar"  @click="gofirst">
        <span class="prebtnicon"></span>
        <span>返回首页</span>
      </div>
      <div class="ordercar1" @click="confirm">
        <span class="oerdertext">选为取车点</span>
        <span class="nextbtnicon"></span>
      </div>
    </div>
  </div>
</template>
<script>
import BMap from 'BMap'
import qs from 'qs'
  export default{
    name: 'rebackpark',
    data () {
      return {
        gettop: '已为您推荐附近的10个取车点',
        parkdetail: [],
        getcarpark: '银河SOHO西侧地面停车场',
//      按钮信息
        buttontxt: '选择还车点&nbsp;&nbsp;&nbsp;&nbsp;>',
        scover: true,
        backpoint: '搜索目的地附近取车点',
        historydata: [],
        listdata: [{'location': '西单', 'park': '北京市东城区南竹杆胡同银河SOHO西侧地面停车场'}, {'location': '西单', 'park': '北京市东城区南竹杆胡同银河SOHO西侧地面停车场'}, {'location': '西单', 'park': '北京市东城区南竹杆胡同银河SOHO西侧地面停车场'}]
      }
    },
    methods: {
      confirm () {
        if(sessionStorage.guestid) {
          sessionStorage.getparkjudge = 'aa'
          sessionStorage.initparkid = sessionStorage.guestid
          sessionStorage.parkingkind = sessionStorage.guestkind
          sessionStorage.parkingkname = sessionStorage.guestparkname
          sessionStorage.getparklng = sessionStorage.guestlng
          sessionStorage.getparklat = sessionStorage.guestlat
          this.$router.push('/Getcar')
        } else {
          this.$router.push('/Getcar')
          console.log('请选择停车场')
        }

      },
      putup () {
        $('#map').on('touchstart', $('.BMap_mask'), function () {
          $('#getcar,.getcar,#rebackpark,.rebackpark').animate({'height': '7.2rem'}, 300)
          $('.carlist,.parklist').css({'overflow-y': 'hidden'})
          $('.rebackbg').show()
        })
      },
      drag: function (e) {
        var startY = e.changedTouches[0].pageY, distY
        var Getcar = document.getElementById('rebackpark')
        Getcar.ontouchmove = function (e) {
          distY = startY - e.changedTouches[0].pageY
        }
        Getcar.ontouchend = function () {
          if (distY > 0) {
            $('#rebackpark,.rebackpark').animate({'height': '14rem'}, 300)
            $('.parklist').css({'overflow': 'scroll'})
            $('.rebackbg').hide()
          }
          document.ontouchmove = null
        }
      },
      searchcover () {
        this.scover = false
        $('.search-in').focus()
        $('.search-in').val('')
        $('#rebackpark').hide()
        $('.search-history').show()
        $('.rebackbg').hide()
        this.historydata = JSON.parse(localStorage.getItem('history1'))  && JSON.parse(localStorage.getItem('history1')).reverse()
      },
      searchcancel () {
        this.scover = true
        $('#rebackpark').show()
        $('.search-history').hide()
        $('.rebackbg').show()
      },
      searchin () {
//        $('.search-list').slideDown()
        $('.search-history').hide()
        if ($('.search-in').val() == '') {
//          $('.search-list').hide()
          $('.search-history').slideDown()
        }
      },
      gofirst () {
        sessionStorage.getparkjudge = 'aa'
        this.$router.push('/Getcar')
      },
      mapready () {
        var arr = []
//         初始还车id等于取车id
//        sessionStorage.guestid = sessionStorage.initparkid
        var mp = new BMap.Map('map2')
        mp.setMapStyle({ styleJson: this.global.mapStyle })
//        用户的位置，用两个session接受backlng；backlat
        var p1 = new BMap.Point(sessionStorage.backlng, sessionStorage.backlat)
        var driving = new BMap.DrivingRoute(mp, {renderOptions: {map: mp, autoViewport: true}})
        mp.centerAndZoom(p1, 14)
        mp.enableScrollWheelZoom(true)
        mp.enableDoubleClickZoom(true)
        // 复杂的自定义覆盖物
        function ComplexCustomOverlay (point, carcount, parkingId, spantext, parkingName, parkingAddress, parkinglat, _parkinglon, parkingkind) {
          this._point = point
          this._text = carcount
          this._spantext = spantext
          this._parkingId = parkingId
          this._parkname = parkingName
          this._parkingAddress = parkingAddress
          this._parkinglat = parkinglat
          this._parkinglon = _parkinglon
          this._parkingkind = parkingkind
        }
        ComplexCustomOverlay.prototype = new BMap.Overlay()
        ComplexCustomOverlay.prototype.initialize = function (map) {
          this._map = map;
          var div = this._div = document.createElement("div")
          div.style.width = "30px"
          div.style.height = "30px"
          div.style.fontSize = "14px"
          div.style.lineHeight = "30px"
          div.className = "mappoint"
          div.setAttribute('data-parkingid', this._parkingId)
          div.setAttribute('data-carCount', this._text)
          div.setAttribute('data-parkname', this._parkname)
          div.setAttribute('data-spantext', this._spantext)
          div.setAttribute('data-parkingAddress', this._parkingAddress)
          div.setAttribute('data-parkinglat', this._parkinglat)
          div.setAttribute('data-parkinglon', this._parkinglon)
          div.setAttribute('data-parkingkind', this._parkingkind)
          div.innerHTML = this._text
          var span = this._span = document.createElement("span");
          span.className = "mapspan"
          span.style.width = "60px"
          span.style.height = "20px"
          span.style.fontSize = "12px"
          span.style.lineHeight = "20px"
          span.innerHTML = this._spantext
          div.appendChild(span)
          mp.getPanes().labelPane.appendChild(div)
          return div
        }
        ComplexCustomOverlay.prototype.draw = function () {
          var map = this._map;
          var pixel = map.pointToOverlayPixel(this._point);
          this._div.style.left = pixel.x - 15 + "px";
          this._div.style.top  = pixel.y - 15 + "px";
        }
//        地图停车场
        var _this = this
        this.axios.post('car/parkingNewListV2.json', qs.stringify({
          positionLon: sessionStorage.backlng,
          positionLat: sessionStorage.backlat,
          userPickCityCode: _this.global.userPickCityCode,
          parkingCount: 29
        }))
          .then(function (res) {
            if (res.data.code == 200) {
              var parkingdata = res.data.modelData.parkingMapVoList[2].parkingList
              var parkingdata1 = res.data.modelData.takeParking
              console.log(res)
//            列表停车场
              _this.parkdetail = parkingdata
//            var p2 = new BMap.Point(parkingdata1.parkingLon, parkingdata1.parkingLat)
//            driving.search(p1, p2)
              for (let i = 0; i < parkingdata.length; i++) {
                mp.addOverlay(new ComplexCustomOverlay(new BMap.Point(parkingdata[i].parkingLon, parkingdata[i].parkingLat), parkingdata[i].carCount, parkingdata[i].parkingId, parkingdata[i].distanceDesc, parkingdata[i].parkingName, parkingdata[i].parkingAddress, parkingdata[i].parkingLat, parkingdata[i].parkingLon, parkingdata[i].parkingKind))
              }
              mp.addOverlay(new ComplexCustomOverlay(new BMap.Point(sessionStorage.backlng, sessionStorage.backlat), '', 'userlocation', 1, 1, 1, 1, 1, 1))
//            坐标点击事件
              $('.mappoint').on('touchstart', function () {
                console.log($(this).attr('data-parkingid'))
                if ($(this).attr('data-parkingid') == 'userlocation') {
                  return false
                }
                $('.mappoint').removeClass('active')
                $(this).addClass('active')
                if ($(this).attr('data-carcount') <= '0') {
                  console.log('没车')
                  return false
                } else {
                  console.log('有车')
                  var p2 = new BMap.Point($(this).attr('data-parkinglon'), $(this).attr('data-parkinglat'))
                  driving.search(p1, p2)
                  sessionStorage.guestid = $(this).attr('data-parkingid')
                  sessionStorage.guestparkname = $(this).attr('data-parkname')
                  sessionStorage.guestkind = $(this).attr('data-parkingkind')
                  sessionStorage.guestlat = $(this).attr('data-parkinglat')
                  sessionStorage.guestlng = $(this).attr('data-parkinglon')
                  console.log($(this).attr('data-parkingid'),$(this).attr('data-parkname'),$(this).attr('data-parkingkind'),$(this).attr('data-parkinglat'),$(this).attr('data-parkinglon'))
                  $('.chose').removeClass('active')
                  $('.chose').each(function () {
                    if ($(this).parents('.backpark').attr('data-parkingid') == sessionStorage.guestid) {
                      $(this).addClass('active')
                      console.log($(this))
                    }
                  })
                }
              })
            }
          })
        $('ul').on('click', '.chose',function () {
          if ($(this).parents('.backpark').attr('data-carcount') == 0){
            console.log('没车')
            return false
          }
          sessionStorage.guestid = $(this).parents('.backpark').attr('data-parkingid')
          sessionStorage.guestparkname = $(this).parents('.backpark').attr('data-parkname')
          sessionStorage.guestkind = $(this).parents('.backpark').attr('data-parkingkind')
          sessionStorage.guestlat = $(this).parents('.backpark').attr('data-parkinglat')
          sessionStorage.guestlng = $(this).parents('.backpark').attr('data-parkinglng')
          $('.chose').removeClass('active')
          $(this).addClass('active')
          var p2 = new BMap.Point($(this).parents('.backpark').attr('data-parkinglng'), $(this).parents('.backpark').attr('data-parkinglat'))
          driving.search(p1, p2)
        })
        mp.addEventListener("touchstart", function () {
          $('#getcar,.getcar,#rebackpark,.rebackpark').animate({'height': '7.2rem'}, 300)
          $('.carlist,.parklist').css({'overflow-y': 'hidden'})
          $('.rebackbg').show()
        })
        // 百度地图API功能
        function G(id) {
          return document.getElementById(id);
        }
        mp.centerAndZoom("城市", 12)
        //         初始化地图,设置城市和地图级别。

        var ac = new BMap.Autocomplete(
//          建立一个自动完成的对象
          {"input" : "suggestId", "location" : mp
          });
        ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
          var str = "";
          var _value = e.fromitem.value;
          var value = "";
          if (e.fromitem.index > -1) {
            value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
          }
          str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

          value = "";
          if (e.toitem.index > -1) {
            _value = e.toitem.value;
            value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
          }
          str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
          G("searchResultPanel").innerHTML = str;
        });

        var myValue;
        ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
          var _value = e.item.value;
          myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
          G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

          setPlace();
        });
        var _this = this
        function setPlace () {
          mp.clearOverlays()    //清除地图上所有覆盖物
          function myFun () {
            var pp = local.getResults().getPoi(0).point    //获取第一个智能搜索的结果
            mp.centerAndZoom(pp, 13)
//            搜索交互开始
            arr = JSON.parse(localStorage.getItem('history1')) || []
            console.log(arr)
            if (arr.length >= 9) {
              arr.splice(9)
            }
            arr.push({'title': local.getResults().getPoi(0).title, 'lng': pp.lng, 'lat': pp.lat})
            localStorage.setItem('history1', JSON.stringify(arr))
            _this.historydata = JSON.parse(localStorage.getItem('history1'))
            _this.axios.post('car/parkingNewListV2.json', qs.stringify({
              positionLon: pp.lng,
              positionLat: pp.lat,
              userPickCityCode: _this.global.userPickCityCode,
              parkingCount: 10
            }))
              .then(function (res) {
                if (res.data.code == 200) {
                  var parkingdata = res.data.modelData.parkingMapVoList[2].parkingList
                  var parkingdata1 = res.data.modelData.takeParking
//                console.log(parkingdata,_this.parkdetail)
                  console.log(res)
                  _this.parkdetail = parkingdata
                  var p2 = new BMap.Point(parkingdata[0].parkingLon, parkingdata[0].parkingLat)
//                driving.search(p1, p2)
                  mp.panTo(p2)
                  for (let i = 0; i < parkingdata.length; i++) {
                    mp.addOverlay(new ComplexCustomOverlay(new BMap.Point(parkingdata[i].parkingLon, parkingdata[i].parkingLat), parkingdata[i].carCount, parkingdata[i].parkingId, parkingdata[i].distanceDesc, parkingdata[i].parkingName, parkingdata[i].parkingAddress, parkingdata[i].parkingLat, parkingdata[i].parkingLon))
                  }
                  mp.addOverlay(new ComplexCustomOverlay(new BMap.Point(sessionStorage.positionLon, sessionStorage.positionLat), '', 'userlocation', 1, 1, 1, 1, 1))
//            坐标点击事件
                  $('.mappoint').on('touchstart', function () {
                    console.log($(this).attr('data-parkingid'))
                    if ($(this).attr('data-parkingid') == 'userlocation'){
                      return false
                    }
                    $('.mappoint').removeClass('active')
                    $(this).addClass('active')
                    if ($(this).attr('data-carcount') == '0') {
                      console.log('没车')
                      return false
                    } else {
                      var p2 = new BMap.Point($(this).attr('data-parkinglon'), $(this).attr('data-parkinglat'))
                      driving.search(p1, p2)
                      sessionStorage.guestid = $(this).attr('data-parkingid')
                      sessionStorage.guestparkname = $(this).attr('data-parkname')
                      sessionStorage.guestkind = $(this).attr('data-parkingkind')
                      sessionStorage.guestlat = $(this).attr('data-parkinglat')
                      sessionStorage.guestlng = $(this).attr('data-parkinglon')
                      console.log($('.chose'))
                      $('.chose').removeClass('active')
                      $('.chose').each(function () {
                        if ($(this).parents('.backpark').attr('data-parkingid') == sessionStorage.guestid) {
                          $(this).addClass('active')
                        }
                      })
                    }
                  })
                }
              })
//            搜索交互结束
            _this.searchcancel()
          }
          var local = new BMap.LocalSearch(mp, { //智能搜索
            onSearchComplete: myFun
          })
          local.search(myValue);
        }
//        点击历史记录
        $('ul').on('click','.historylist',function () {
          _this.searchcancel()
          var hislng = $(this).attr('data-lng')
          var hislat = $(this).attr('data-lat')
          mp.clearOverlays()
          mp.centerAndZoom((hislng,hislat), 13)
          _this.axios.post('car/parkingNewListV2.json', qs.stringify({
            positionLon: hislng,
            positionLat: hislat,
            userPickCityCode: _this.global.userPickCityCode,
            parkingCount: 9
          }))
            .then(function (res) {
              if (res.data.code == 200) {
                var parkingdata = res.data.modelData.parkingMapVoList[2].parkingList
                _this.parkdetail = parkingdata
                var p2 = new BMap.Point(parkingdata[0].parkingLon, parkingdata[0].parkingLat)
//                driving.search(p1, p2)
                mp.panTo(p2)
                for (let i = 0; i < parkingdata.length; i++) {
                  mp.addOverlay(new ComplexCustomOverlay(new BMap.Point(parkingdata[i].parkingLon, parkingdata[i].parkingLat), parkingdata[i].carCount, parkingdata[i].parkingId, parkingdata[i].distanceDesc, parkingdata[i].parkingName, parkingdata[i].parkingAddress, parkingdata[i].parkingLat, parkingdata[i].parkingLon))
                }
                mp.addOverlay(new ComplexCustomOverlay(new BMap.Point(sessionStorage.positionLon, sessionStorage.positionLat), '', 'userlocation', 1, 1, 1, 1, 1))
//            坐标点击事件
                $('.mappoint').on('touchstart', function () {
                  console.log($(this).attr('data-parkingid'))
                  if ($(this).attr('data-parkingid') == 'userlocation'){
                    return false
                  }
                  $('.mappoint').removeClass('active')
                  $(this).addClass('active')
                  if ($(this).attr('data-carcount') <= '0') {
                    console.log('没车')
                    return false
                  } else {
                    var p2 = new BMap.Point($(this).attr('data-parkinglon'), $(this).attr('data-parkinglat'))
                    driving.search(p1, p2)
                    sessionStorage.guestid = $(this).attr('data-parkingid')
                    sessionStorage.guestparkname = $(this).attr('data-parkname')
                    sessionStorage.guestkind = $(this).attr('data-parkingkind')
                    sessionStorage.guestlat = $(this).attr('data-parkinglat')
                    sessionStorage.guestlng = $(this).attr('data-parkinglon')
                    console.log($('.chose'))
                    $('.chose').removeClass('active')
                    $('.chose').each(function () {
                      if ($(this).parents('.backpark').attr('data-parkingid') == sessionStorage.guestid) {
                        $(this).addClass('active')
                      }
                    })
                  }
                })
              }
            })
//            点击历史记录搜索交互结束
        })
      }
    },
    mounted: function () {
      this.mapready()
    }
  }
</script>
<style lang="scss">
  @import "../style/scss/getcarpark";
  .chose{
    background: url("../../static/image/icon_select.png");
    -webkit-background-size: cover;
    background-size: cover;
  }
  .chose.active{
    background: url("../../static/image/icon_selected.png");
    -webkit-background-size: cover;
    background-size: cover;
  }
  .moneyicon{
    background: url("../../static/image/icon_payback.png");
    -webkit-background-size: cover;
    background-size: cover;
  }
  .search-icon{
    background: url("../../static/image/icon_search.png");
    -webkit-background-size: cover;
    background-size: cover;
  }
  .prebtnicon{
    width:14px;
    height:24px;
    display: inline-block;
    background: url("../../static/image/icon_select_back.png");
    -webkit-background-size: cover;
    background-size: cover;
    margin-left:40px;
    margin-top:38px;
    margin-right:20px;
  }
  .nextbtnicon{
    width:14px;
    height:24px;
    display: inline-block;
    background: url("../../static/image/icon_next.png");
    -webkit-background-size: cover;
    background-size: cover;
    margin-left:46px;
    margin-top:38px;
  }
</style>
